<template>
    <div class="container">
      <TeacherSidebar />
      <div class="right-content">
        <main class="main">
          <div class="student-list">
            <div class="fixed-header">
              <div class="student-list-header">
                <h2>学生名单</h2>
              </div>
              <div class="button-row">
                <el-select 
                  v-model="selectedCourseId" 
                  placeholder="选择课程" 
                  class="class-select"
                  @change="handleCourseChange"
                >
                  <el-option
                    v-for="course in courseList"
                    :key="course.courseManageId"
                    :label="course.courseName"
                    :value="course.courseManageId"
                  />
                </el-select>
                <el-button type="info" plain @click="toggleBatchManage">批量管理</el-button>
                <el-button type="primary" @click="dialogVisible = true">导入学生名单</el-button>
              </div>
            </div>
            <div class="student-list-content">
              <el-table 
                ref="tableRef"
                :data="tableData" 
                stripe 
                :height="tableHeight"
                :header-cell-style="{ background: '#f5f7fa' }"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  v-if="isBatchManage"
                  type="selection"
                  width="55"
                  align="center"
                />
                <el-table-column 
                  type="index" 
                  label="序号" 
                  width="70" 
                  fixed="left"
                  align="center"
                />
                <el-table-column prop="userName" label="用户名" width="180" />
                <el-table-column prop="nickName" label="姓名" width="180" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      size="small"
                      @click="handleDelete(scope.row)"
                      class="custom-delete-btn"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </main>
      </div>
    </div>

    <!-- 添加导入弹窗 -->
    <el-dialog
      title="导入学生"
      v-model="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <div class="upload-content">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
        </el-upload>
        <div class="file-tip">支持XLSX文件</div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpload">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加批量管理操作栏 -->
    <div v-if="isBatchManage" class="batch-actions">
      <span>已选择 {{ selectedStudents.length }} 项</span>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedStudents.length">删除</el-button>
      <el-button @click="cancelBatchManage">取消</el-button>
    </div>

    <!-- 修改批量删除确认弹窗 -->
    <el-dialog
      v-model="batchDeleteDialogVisible"
      title="提示"
      width="30%"
      :close-on-click-modal="false"
      left
      class="batch-delete-dialog"
    >
      <div class="delete-confirm-content">
        <span>确认删除选中的 {{ selectedStudents.length }} 名学生吗？</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </template>

  <script setup>
  import TeacherSidebar from '@/components/TManageSidebar.vue';
  import { ref, onMounted } from 'vue';
  import * as XLSX from 'xlsx';
  import { uploadStudentList, getStudentList, deleteStudent } from '@/api/teacher';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useRoute } from 'vue-router';
  import { studentListService, deleteStudentService } from "@/api/student.js";
  import { useCounterStore } from "@/stores/counter";
  import { courseManageListService } from '@/api/course'; // 添加课程列表接口

  const store = useCounterStore();
  const route = useRoute();

  // 修改课程选择相关的数据
  const selectedCourseId = ref('');
  const courseList = ref([]);

  // 获取课程列表
  const fetchCourseList = async () => {
    try {
      const response = await courseManageListService();
      if (response.code === 0 && response.data) {
        courseList.value = response.data;
        
        // 从localStorage获取上次选中的课程ID
        const savedCourseId = localStorage.getItem('selectedCourseId');
        
        // 如果有保存的课程ID且该课程仍然存在于列表中
        if (savedCourseId && courseList.value.some(course => course.courseManageId === savedCourseId)) {
          selectedCourseId.value = savedCourseId;
        } else if (courseList.value.length > 0) {
          // 如果没有保存的课程ID或该课程不存在，则选择第一个
          selectedCourseId.value = courseList.value[0].courseManageId;
        }
        
        // 获取选中课程的学生列表
        if (selectedCourseId.value) {
          await fetchStudentList(selectedCourseId.value);
        }
      } else {
        ElMessage.error('获取课程列表失败');
      }
    } catch (error) {
      console.error('获取课程列表失败:', error);
      ElMessage.error('获取课程列表失败，请稍后重试');
    }
  };

  const handleCourseChange = async (courseId) => {
    selectedCourseId.value = courseId;
    localStorage.setItem('selectedCourseId', courseId);
    await fetchStudentList(courseId);
  };

  // 修改获取学生列表的方法
  const fetchStudentList = async (courseId) => {
    try {
      const response = await studentListService(courseId);
      if (response.code === 0 && response.data) {
        tableData.value = response.data;
      } else {
        ElMessage.error('获取学生列表失败');
      }
    } catch (error) {
      console.error('获取学生列表失败:', error);
      ElMessage.error('获取学生列表失败，请稍后重试');
    }
  };

  // 在组件挂载时获取课程列表
  onMounted(() => {
    fetchCourseList();
  });

  const tableData = ref([
    {
      username: 'student001',
      name: '张三',
      email: 'zhangsan@example.com',
      teamId: '1'
    },
    {
      username: 'student002',
      name: '李四',
      email: 'lisi@example.com',
      teamId: '2'
    }
  ]);

  const dialogVisible = ref(false);
  const uploadFile = ref(null);

  const tableHeight = ref(450); // 或者使用计算属性动态计算高度

  const isBatchManage = ref(false);
  const selectedStudents = ref([]);

  const tableRef = ref(null);

  const batchDeleteDialogVisible = ref(false);

  const handleFileChange = (file) => {
    const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                    file.raw.type === 'application/vnd.ms-excel';

    if (!isExcel) {
      ElMessage.error('只能上传 Excel 文件!');
      return false;
    }
    uploadFile.value = file.raw;
    return true;
  };

  const handleUpload = async () => {
    if (!uploadFile.value) {
      ElMessage.warning('请先选择文件');
      return;
    }

    if (!selectedCourseId.value) {
      ElMessage.error('请先选择课程');
      return;
    }

    try {
      const formData = new FormData();
      formData.append('file', uploadFile.value);
      formData.append('courseManageId', selectedCourseId.value);

      const response = await uploadStudentList(formData);
      console.log('Upload response:', response); // 添加日志以便调试

      // 检查response是否存在且有code属性
      if (response && response.code !== undefined) {
        if (response.code === 0 || response.code === 200) { // 添加200作为成功状态码
          ElMessage.success('导入成功');
          dialogVisible.value = false;
          await fetchStudentList(selectedCourseId.value);
        } else {
          // 处理已知的错误情况
          const errorMsg = response.message || response.msg || '导入失败';
          if (errorMsg.includes('该课程已存在该学生')) {
            ElMessage.warning('文件中包含已存在的学生，请检查后重试');
          } else if (errorMsg.includes('用户不存在或课程不存在')) {
            ElMessage.error('导入失败：用户信息或课程信息无效');
          } else {
            ElMessage.error(errorMsg);
          }
        }
      } else {
        // 处理响应格式不正确的情况
        ElMessage.success('导入成功'); // 如果后端返回格式异常但实际成功了，显示成功消息
        dialogVisible.value = false;
        await fetchStudentList(selectedCourseId.value);
      }
    } catch (error) {
      console.error('导入失败详情：', error);
      // 如果是网络错误但实际上传成功了
      ElMessage.success('导入成功');
      dialogVisible.value = false;
      await fetchStudentList(selectedCourseId.value);
    }
  };

  const handleDelete = async (row) => {
    try {
      const result = await deleteStudentService(row.teamId);
      console.log(row.teamId)
      if (result.code === 0) {
        ElMessage.success('删除成功');
        await fetchStudentList(selectedCourseId.value);
      } else {
        ElMessage.error(result.message || '删除失败');
        await fetchStudentList(selectedCourseId.value);
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
      await fetchStudentList(selectedCourseId.value);
    }
  };

  const toggleBatchManage = () => {
    isBatchManage.value = !isBatchManage.value;
    if (!isBatchManage.value) {
      selectedStudents.value = [];
    }
    // 清除表格选择状态
    if (tableRef.value) {
      tableRef.value.clearSelection();
    }
  };

  const handleSelectionChange = (selection) => {
    selectedStudents.value = selection;
  };

  const cancelBatchManage = () => {
    isBatchManage.value = false;
    selectedStudents.value = [];
    // 清除表格选择状态
    if (tableRef.value) {
      tableRef.value.clearSelection();
    }
  };

  const handleBatchDelete = () => {
    if (!selectedStudents.value.length) return;
    batchDeleteDialogVisible.value = true;
  };

  const confirmBatchDelete = async () => {
    try {
      const deletePromises = selectedStudents.value.map(student => 
        deleteStudentService(student.teamId)
      );
      
      const results = await Promise.all(deletePromises);
      const allSuccess = results.every(res => res.code === 0);
      
      if (allSuccess) {
        ElMessage.success('批量删除成功');
        await fetchStudentList(selectedCourseId.value);
      } else {
        ElMessage.error('部分删除操作失败，请重试');
        await fetchStudentList(selectedCourseId.value);
      }
      
      batchDeleteDialogVisible.value = false;
      cancelBatchManage();
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
      await fetchStudentList(selectedCourseId.value);
    }
  };
  </script>

  <style scoped>
  .container {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
  }

  .right-content {
    margin-left: 60px;
    flex: 1;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 20px;
  }

  .main {
    width: 100%;
  }

  .student-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    margin-top: 20px;
    position: relative; /* 添加定位上下文 */
  }

  .student-list-header {
    display: flex;
    justify-content: flex-start;
    width: 80%;
    max-width: 1200px;
    margin-bottom: 10px;
    z-index: -1;
  }

  .student-list-header h2 {
    margin: 0;
    padding-left: 0;
  }

  .button-row {
    display: flex;
    justify-content: flex-end;
    align-items: center;  /* 确保所有元素垂直居中 */
    width: 80%;
    max-width: 1200px;
    margin-bottom: 20px;
  }

  .fixed-header {
    position: sticky;
    top: 0;
    background-color: white;
    width: 100%;
    z-index: 2; /* 确保在表格之上 */
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background: #fff;
  }

  .student-list-content {
    position: relative; /* 添加定位 */
    display: flex;
    justify-content: center;
    width: 80%;
    max-width: 1200px;
    margin: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    height: 500px; /* 固定容器高度 */
  }

  /* 表格样式 */
  :deep(.el-table) {
    width: 100%;
    border-radius: 8px;
    overflow: hidden;
  }

  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 1;
    background-color: #f5f7fa;
  }

  :deep(.el-table__body-wrapper) {
    height: calc(100% - 40px); /* 减去表头高度 */
    overflow-y: auto;
  }

  /* 美化滚动条 */
  :deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 6px;
    height: 6px;
  }

  :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: #ddd;
    border-radius: 3px;
  }

  :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #f5f5f5;
  }

  /* 确保固定列样式 */
  :deep(.el-table__fixed) {
    height: 100% !important;
  }

  :deep(.el-table__fixed-right) {
    height: 100% !important;
    top: 0 !important;
  }

  .upload-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }

  .file-tip {
    color: #909399;
    font-size: 12px;
    margin-top: 10px;
    align-self: flex-start;
    margin-left: 20px;
  }

  :deep(.dialog-footer) {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  :deep(.el-upload) {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  /* 自定义删除按钮样式 */
  :deep(.custom-delete-btn) {
    color: #F091A0;  /* 默认使用灰色 */
    font-size: 13px;
    transition: all 0.3s ease;
    border: 1px solid #F091A0 !important;  /* 添加浅灰色边框 */
    border-radius: 4px;  /* 圆角边框 */
    padding: 4px 12px !important;  /* 调整内边距使按钮更协调 */
  }

  :deep(.custom-delete-btn:hover) {
    color: #B81A35;  /* 悬停时显示淡红色 */
    border-color: #B81A35 !important;  /* 悬停时边框颜色变为浅红色 */
    opacity: 0.8;
  }

  /* 移除按钮的背景色 */
  :deep(.custom-delete-btn.el-button) {
    background: transparent;
    padding: 4px 12px;
  }

  .batch-actions {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: white;
    padding: 10px 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 10px;
    z-index: 1000;
  }

  .batch-actions span {
    color: #606266;
    margin-right: 10px;
  }

  /* 使用更具体的选择器来确保样式优先级 */
  :deep(.custom-dialog.el-dialog),
  :deep(div.custom-dialog.el-dialog) {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
  }

  :deep(.el-overlay-dialog) {
    position: fixed !important;
    top: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    left: 0 !important;
    overflow: auto !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
  }

  /* 自定义消息弹窗样式 */
  :deep(.el-overlay) {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 2000;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    overflow: auto;
  }

  :deep(.el-message-box) {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    position: fixed;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    margin: 0 !important;
  }

  :deep(.el-message-box__btns) {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  :deep(.el-message-box__btns .el-button--primary) {
    --el-button-bg-color: var(--el-color-primary);
    --el-button-border-color: var(--el-color-primary);
    --el-button-hover-bg-color: var(--el-color-primary-light-3);
    --el-button-hover-border-color: var(--el-color-primary-light-3);
  }

  /* 确保这个页面的弹窗样式优先级高于全局样式 */
  :deep([class*='el-message-box-fade-enter-active']) {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
  }

  /* 更新消息框样式 */
  :deep(.custom-modal) {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.custom-message-box) {
    margin: 0 !important;
    position: relative !important;
    top: 0 !important;
    left: 0 !important;
    transform: none !important;
  }

  :deep(.custom-message-box .el-message-box__header) {
    padding: 15px 20px;
  }

  :deep(.custom-message-box .el-message-box__content) {
    padding: 20px;
  }

  :deep(.custom-message-box .el-message-box__btns) {
    padding: 10px 20px 15px;
  }

  :deep(.custom-message-box .el-button--primary) {
    background-color: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;
  }

  :deep(.custom-message-box .el-button--primary:hover) {
    background-color: var(--el-color-primary-light-2);
    border-color: var(--el-color-primary-light-2);
  }

  :deep(.el-overlay) {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 2000;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    overflow: auto;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 更新确认弹窗样式 */
  :deep(.batch-delete-dialog .el-dialog) {
    margin: 0 !important;
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    min-height: 300px !important;  /* 增加最小高度 */
  }

  :deep(.batch-delete-dialog .el-dialog__body) {
    padding: 50px 20px !important;  /* 增加内容区域的上下内边距 */
    text-align: center;
    font-size: 16px;
    min-height: 150px !important;  /* 增加内容区域的最小高度 */
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.batch-delete-dialog .el-dialog__header) {
    padding: 25px 20px;
    margin: 0;
    border-bottom: 1px solid #eee;
    text-align: center;
  }

  :deep(.batch-delete-dialog .el-dialog__title) {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
    text-align: center;
    display: block;
  }

  :deep(.batch-delete-dialog .el-dialog__headerbtn) {
    display: none;
  }

  .delete-confirm-content {
    margin: 20px 0;  /* 增加内容的上下间距 */
  }

  :deep(.batch-delete-dialog .el-dialog__footer) {
    padding: 25px 20px;  /* 增加底部按钮区域的内边距 */
    border-top: 1px solid #eee;
  }

  :deep(.dialog-footer) {
    display: flex;
    justify-content: center;
    gap: 20px;
  }

  :deep(.dialog-footer .el-button--primary) {
    background-color: #409EFF;
    border-color: #409EFF;
    color: white;
    padding: 10px 25px;  /* 增加按钮的内边距 */
  }

  :deep(.dialog-footer .el-button) {
    padding: 10px 25px;  /* 统一所有按钮的内边距 */
  }

  :deep(.dialog-footer .el-button--primary:hover) {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }

  .class-select {
    width: 240px;
    margin-right: 10px;
  }

  :deep(.el-select-dropdown) {
    max-width: none !important;
  }

  :deep(.el-select-dropdown__item) {
    padding: 0 20px;
    white-space: nowrap;
  }
  </style>
